package com.raising.framework.controller;

import com.raising.framework.entity.JsonMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 基础controller
 * @author GaoYuan
 */
public class BaseController {
    /**Log4j日志处理*/
    protected org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 管理基础路径
     */
    @Value("${adminPath}")
    protected String adminPath;
    /**申报路径*/
    @Value("${applyPath}")
    protected String applyPath;
    /**审核平台*/
    @Value("${auditPath}")
    protected String auditPath;
    /**职称管理平台*/
    @Value("${managerPath}")
    protected String managerPath;
    /**评审路径*/
    @Value("${reviewPath}")
    protected String reviewPath;
    /**上传平台*/
    @Value("${uploadPath}")
    protected String uploadPath;
    /**投票平台路径*/
    @Value("${votePath}")
    protected String votePath;
    /**工作流路径*/
    @Value("${workflowPath}")
    protected String workflowPath;


    /**
     * 前端基础路径
     */
    @Value("${frontPath}")
    protected String frontPath;

    /**
     * 前端开放平台路径（个人中心）
     */
    @Value("${accountPath}")
    protected String accountPath;

    /**
     * rest接口路径
     */
    @Value("${restPath}")
    protected String restPath;

    /**
     * 前端URL后缀
     */
    @Value("${urlSuffix}")
    protected String urlSuffix;

    /**
     * 客户端返回JSON字符串
     *
     * @param response
     * @param object
     * @return String
     */
    protected String renderString(HttpServletResponse response, Object object) {
        return renderString(response, JsonMapper.toJsonString(object),
                "application/json");
    }

    /**
     * 返回JSONP的数据
     *
     * @param response
     * @param object
     * @param callback
     * @return
     */
    protected String renderString(HttpServletResponse response, Object object,
                                  String callback) {
        return renderString(response,
                callback + "(" + JsonMapper.toJsonString(object) + ")",
                "application/text");
    }

    /**
     * 客户端返回字符串
     *
     * @param response
     * @param string
     * @return
     */
    protected String renderString(HttpServletResponse response, String string,
                                  String type) {
        try {
            response.reset();
            response.setContentType(type);
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
            return null;
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * 获得用户远程地址
     */
    public static String getRemoteAddr(HttpServletRequest request) {
        String remoteAddr = request.getHeader("X-Real-IP");
        if (StringUtils.isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("X-Forwarded-For");
        } else if (StringUtils.isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("Proxy-Client-IP");
        } else if (StringUtils.isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("WL-Proxy-Client-IP");
        }
        return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
    }

    /**
     * 添加Model消息
     *
     * @param messages
     */
    protected void addMessage(Model model, String... messages) {
        StringBuilder sb = new StringBuilder();
        for (String message : messages) {
            sb.append(message).append(messages.length > 1 ? "<br/>" : "");
        }
        model.addAttribute("msg", sb.toString());
    }

    /**
     * 添加Flash消息
     *
     * @param messages
     */
    protected void addMessage(RedirectAttributes redirectAttributes,
                              String... messages) {
        StringBuilder sb = new StringBuilder();
        for (String message : messages) {
            sb.append(message).append(messages.length > 1 ? "<br/>" : "");
        }
        redirectAttributes.addFlashAttribute("msg", sb.toString());
    }

//	/**
//	 * 需要数据过滤，赋值数据权限控制数据
//	 * 查询所属机构上级机构的所属数据【查看公司数据】
//	 * @author gaoy
//	 * 2017 2017-5-15 下午11:48:47
//	 * @param t
//	 */
//	public void setDataFilter_Company(@SuppressWarnings("rawtypes") DataEntity t){
//		User user = UserUtils.getLoginUser();
//		if(user==null||user.getOrganization()==null||user.getOrganization().getParentIds()==null||"".equals(user.getOrganization().getParentIds())){
//			t.setOrgParentParentIds("----");
//		}else{
//			t.setOrgParentParentIds(user.getOrganization().getParentParentIds());
//		}
//	}
//
//	/**
//	 * 需要数据过滤，赋值数据权限控制数据
//	 * 只查看自己组织机构的数据【查看部门数据】
//	 * @author gaoy
//	 * 2017 2017-6-13 上午10:22:34
//	 * @param t
//	 */
//	public void setDataFilter_Banch(@SuppressWarnings("rawtypes") DataEntity t){
//		User user = UserUtils.getLoginUser();
//		if(user==null||user.getOrganization()==null||user.getOrganization().getParentIds()==null||"".equals(user.getOrganization().getParentIds())){
//			t.setOrgParentIds("----");
//		}else{
//			t.setOrgParentIds(user.getOrganization().getParentIds());
//		}
//	}
//
//	/**
//	 * 授权管理数据过滤[没有时只展示自己创建的]
//	 * @author gaoy
//	 * 2017 2017-6-13 上午9:58:16
//	 * @param t
//	 */
//	public void setDataFilter_Manage(@SuppressWarnings("rawtypes") DataEntity t){
//		User user = UserUtils.getLoginUser();
//		String manageOrgIdsStr = user.getManageOrgIdsStr();
//		if(user.isAdmin()){
//
//		}else if(manageOrgIdsStr!=null && !"".equals(manageOrgIdsStr)){
//			User user_now = new User();
//			user_now.setManageOrgIdsStr(user.getManageOrgIdsStr());
//			t.setUser(user_now);
//		}else{
//			t.setCreateBy(user.getId());
//		}
//	}

}
